<?php //
namespace backend\controllers;

use Yii;
use backend\models\Admin;
use backend\base\BaseBackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Security;
use base\YiiMobo;

class AdminController extends BaseBackendController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */


    public function behaviors()
    {
        return ['verbs' => ['class' => VerbFilter::className(), 'actions' => ['delete' => ['post'], ], ], ];
    }


    /**
     * 添加数据内容.
     * 添加数据库内容的表单提交处理
     * 模板文件通常为  views/schoolpost/_form.php
     */
    public function actionCreate()
    {
        /**
         *  $model = new Admin;
         *         if (isset($_POST['Admin'])) {
         *             if ($model->create($_POST['Admin'])) {
         *                 $this->OperTips('/admin/index');
         *             }
         *         }
         *         return $this->render('_form', array('model' => $model, ));
         */
       	$model = self::findModel();
        echo $this->formSave($model);
    }
    /**
     * 添加数据内容.
     * 添加数据库内容的表单提交处理
     * 模板文件通常为  views/schoolpost/_form.php
     */
    public function actionUpdate($id)
    {

        if (isset($_POST['Admin'])) {
            $user = Admin::findByUsername(yii::$app->user->identity->username);
            if ($_POST['Admin']['password']) {
                $user->setPassword($_POST['Admin']['password']);
            }
            if ($_POST['Admin']['email']) {
                $user->email = $_POST['Admin']['email'];
            }
            if ($user->save()) {
                $this->OperTips('/admin/index');
            }
        }
        $model = self::findModel($id);
        return $this->render('_form', array('model' => $model, ));
    }

    public function actionCheckname($username, $id)
    {
        $userrole = "select * from {{%admin}} where username = '$username'" . ($id ?
            " and id!=$id" : '');
        echo Yii::$app->db->createCommand($userrole)->queryAll() ? 'false' : 'true';
    }


    /**
     * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/schoolpost/index.php
     */
    public function actionIndex()
    {
        /**
         * $sql = 'select * from `o2o_admin`';
         * $orderby = '';
         * $models['search'] = isset($_REQUEST['search']) ? $_REQUEST['search'] : [];
         * $models = array_merge(YiiMobo::pageRows($sql, $orderby), $models);
         * print_r($models);exit;
         * echo $this->render('index', ['models'=>$models]);
         */
        $param['sql'] = 'select * from {{%admin}}';
        $param['order'] = 'order by id desc';
        $param['param']['search'] = isset($_REQUEST['search']) ? $_REQUEST['search'] :
            '';
        //    if(isset($_REQUEST['search'])){
//                print_r($_REQUEST['search']);exit;
//            }
        $param['pageparam']['PageSize'] = 10;
        echo $this->pageView('index', $param);

    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    protected function findModel($id = null)
    {
        $model = $id ? Admin::findOne($id) : new Admin;
        if ($model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'admin-form') {
            echo CActiveForm::validate($model);
            Yii::$app->end();
        }
    }

    /**
     * 修改密码页面
     */
    public function actionRepass()
    {

        if (Yii::$app->request->post()) {
            $user = Admin::findByUsername(yii::$app->user->identity->username);
            if (!$user || !$user->validatePassword($_POST['Admin']['oldpass'])) {
                $this->OperTips(['backurl' => '/admin/repass', 'error' => 1, 'title' =>
                    '原密码验证失败', 'content' => '']);
            }
            $user->setPassword($_POST['Admin']['renewpass']);
            if ($user->save()) {
                $this->OperTips(['backurl' => 'login/logout', 'top_href' => 1]);
            }
        }
        if (!Yii::$app->user->isGuest) {
            return $this->render('repass');
        } else {
            echo "请先登入！";
        }
    }


}
